//
//  UIView+BCScreenshot.m
//  BCUIKit
//
//  Created by chun.chen on 2020/10/19.
//

#import "UIView+BCScreenshot.h"

@implementation UIView (BCScreenshot)

- (UIImage *)bc_screenshot {
    if (self.bounds.size.width<0.5 || self.bounds.size.height<0.5) {
        [self layoutIfNeeded];
    }
    return [self bc_screenshotForCroppingRect:self.bounds];
}
- (UIImage *)bc_screenshotForCroppingRect:(CGRect)rect {
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    // Create a graphics context and translate it the view we want to crop so
    // that even in grabbing (0,0), that origin point now represents the actual
    // cropping origin desired:
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (context == NULL) return nil;
    CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
    
    [self layoutIfNeeded];
    [self.layer renderInContext:context];
    
    UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshotImage;
}
@end
